package com.LONE.spring6.tx.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

/**
 * @Project ：learn_spring
 * @File ：BookDaoImpl.java
 * @IDE ：IntelliJ IDEA
 * @Author ：自由如风间
 * @Date ：2025/4/5 10:56
 * @Description ：For study.
 */

@Repository
public class BookDaoImpl implements BookDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 根据图书id获取图书价格
     * @param bookId 图书id
     * @return 图书价格
     */
    @Override
    public Integer getPriceByBookId(Integer bookId) {
        String sql = "select price from t_book where book_id = ?";
        return jdbcTemplate.queryForObject(sql, Integer.class, bookId);
    }

    /**
     * 根据用户id查询用户余额
     * @param userId 用户id
     * @return 用户余额
     */
    @Override
    public Integer getBalanceByUserId(Integer userId) {
        String sql = "select balance from t_user where user_id = ?";
        return jdbcTemplate.queryForObject(sql, Integer.class, userId);
    }

    /**
     * 更新库存
     * @param bookId 图书id
     */
    @Override
    public void updateStock(Integer bookId) {
        String sql = "update t_book set stock=stock-1 where book_id=?";
        jdbcTemplate.update(sql, bookId);
    }

    /**
     * 更新用户余额
     * @param userId 用户id
     * @param price 图书价格
     */
    @Override
    public void updateUserBalance(Integer userId, Integer price) {
        String sql = "update t_user set balance=balance-? where user_id=?";
        jdbcTemplate.update(sql, price, userId);
    }
}
